//  DB  库
const config = require('./config')

const MongoClient = require('mongodb').MongoClient
const ObjectID = require('mongodb').ObjectID

class Db {
  static getInstance() {
    // 单例模式  解决多次实例化不共享的问题
    if (!Db.instance) {
      Db.instance = new Db()
    }
    return Db.instance
  }

  constructor() {
    this.dbClient = null
    this.connect()
  }
  /* 链接数据库 */
  connect() {
    let _that = this
    return new Promise((resolve, reject) => {
      if (!_that.dbClient) {
        MongoClient.connect(config.dbUrl, (err, client) => {
          if (err) {
            reject('错误链接', err)
          } else {
            _that.dbClient = client.db(config.dbName)
            resolve(_that.dbClient)
          }
        })
      } else {
        resolve(_that.dbClient)
      }
    })
  }
  /* 查找 */
  find(collectionName, json = {}) {
    let _that = this

    return new Promise((resolve, reject) => {
      _that.connect().then((db) => {
        const res = db.collection(collectionName).find(json)
        res.toArray((err, data) => {
          if (err) {
            reject(err)
          }
          resolve(data)
        })
      })
    })
  }
  /* 新增 */
  insert(collectionName, json) {
    return new Promise((resolve, reject) => {
      this.connect().then((db) => {
        db.collection(collectionName).insertOne(json, (err, data) => {
          if (err) {
            reject(err)
          }
          resolve(data)
        })
      })
    })
  }
  /* 更新数据 */
  update(collectionName, beforeUpdate, lastUpdate) {
    return new Promise((resolve, reject) => {
      this.connect().then((db) => {
        db.collection(collectionName).updateOne(
          beforeUpdate,
          {
            $set: lastUpdate,
          },
          (err, data) => {
            if (err) {
              reject(err)
            }
            resolve(data)
          }
        )
      })
    })
  }
  /* 删除 */
  remove(collectionName, json) {
    return new Promise((resolve, reject) => {
      this.connect().then((db) => {
        db.collection(collectionName).removeOne(json, (err, data) => {
          if (err) {
            reject(err)
          }
          resolve(data)
        })
      })
    })
  }
  /* 获取 _id */
  getObjectID(id) {
    return new ObjectID(id)
  }
}

module.exports = Db.getInstance()
